<?php

namespace app\like\controllers;

class Index
{
    /**
     * 点赞
     */
    public function love()
    {
        login_check();

        $data['user_id']    = session('user_id');
        $data['post_id']    = segment(3, 'int');
        $data['created_at'] = time();

        $like  = model('like');
        $liked = $like->checkIfLiked($data['post_id']);

        // 未点赞
        if (!$liked) {
            try {
                if ($like->add($data)) {
                    return json('点赞成功', 'success');
                }
            } catch (\Throwable $th) {
                return json('点赞失败');
            }
        }

        // 已点赞
        if ($liked) {
            try {
                if ($like->del($data)) {
                    return json('取消赞成功', 'success');
                }
            } catch (\Throwable $th) {
                return json('取消赞失败');
            }
        }
    }
}